<template>
  <div id="app">
    <!-- 交易总额统计区域 -->
    <div class="chart-container">
      <h2 style="text-align: center">交易额统计</h2>
      <div class="search-boxes">
        <el-select
          v-model="transactionDept"
          @change="handleChange($event, 'department_id', '交易额')"
          clearable
          placeholder="请选择科室"
        >
          <el-option
            v-for="dept in departMentArr"
            :key="dept.id"
            :label="dept.name"
            :value="dept.id"
          ></el-option>
        </el-select>
        <el-select
          v-model="transactionDoctor"
          placeholder="请选择医生"
          @change="handleChange($event, 'doctor_id', '交易额')"
        >
          <el-option
            v-for="doctor in doctors"
            :key="doctor.id"
            :label="doctor.name"
            :value="doctor.id"
          ></el-option>
        </el-select>
        <!--        <el-select v-model="transactionCategory" placeholder="请选择类别">
          <el-option
            v-for="category in transactionCategories"
            :key="category"
            :label="category"
            :value="category"
          ></el-option>
        </el-select> -->
        <el-date-picker
          v-model="transactionDateRange"
          type="monthrange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="handleChange($event, 'time', '交易额')"
        ></el-date-picker>
        <el-button @click="handleTransactionQuery" type="primary"
          >查询</el-button
        >
      </div>
      <div id="bar-chart" class="chart"></div>
    </div>
    <!-- 接诊总量统计区域 -->
    <div class="chart-container">
      <h2 style="text-align: center">接诊量统计</h2>
      <div class="search-boxes">
        <el-select
          v-model="receptionDept"
          @change="handleChange($event, 'department_id', '接诊量')"
          placeholder="请选择科室"
        >
          <el-option
            v-for="dept in departMentArr"
            :key="dept.id"
            :label="dept.name"
            :value="dept.id"
          ></el-option>
        </el-select>
        <el-select
          v-model="receptionDoctor"
          @change="handleChange($event, 'doctor_id', '接诊量')"
          placeholder="请选择医生"
        >
          <el-option
            v-for="doctor in doctors"
            :key="doctor.id"
            :label="doctor.name"
            :value="doctor.id"
          ></el-option>
        </el-select>
        <!--     <el-date-picker
          v-model="receptionDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker> -->
        <el-date-picker
          v-model="receptionDateRange"
          type="monthrange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="handleChange($event, 'time', '接诊量')"
        ></el-date-picker>
        <el-button @click="handleReceptionQuery" type="primary">查询</el-button>
      </div>
      <div id="line-chart-1" class="chart"></div>
    </div>
    <!-- 开单总量统计区域 -->
    <div class="chart-container">
      <h2 style="text-align: center">开单量统计</h2>
      <div class="search-boxes">
        <el-select
          v-model="orderDept"
          @change="handleChange($event, 'department_id', '开单量')"
          placeholder="请选择科室"
        >
          <el-option
            v-for="dept in departMentArr"
            :key="dept.id"
            :label="dept.name"
            :value="dept.id"
          ></el-option>
        </el-select>
        <el-select
          v-model="orderDoctor"
          @change="handleChange($event, 'doctor_id', '开单量')"
          placeholder="请选择医生"
        >
          <el-option
            v-for="doctor in doctors"
            :key="doctor.id"
            :label="doctor.name"
            :value="doctor.id"
          ></el-option>
        </el-select>
        <el-date-picker
          v-model="orderDateRange"
          type="monthrange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="handleChange($event, 'time', '开单量')"
        ></el-date-picker>
        <el-button @click="handleOrderQuery" type="primary">查询</el-button>
      </div>
      <div id="line-chart-2" class="chart"></div>
    </div>
  </div>
</template>

<script>
import {
  ApigetMoneyStatistics,
  ApigetOrderCountStatistics,
  ApigetAdviceCountStatistics,
  ApiDepartment,
  ApigetDoctorList,
} from "../../api/index";
import * as echarts from "echarts";

export default {
  data() {
    return {
      xAxisData: [],
      totalTransactionAmount: 0,
      totalReceptionAmount: 0,
      totalOrderAmount: 0,
      departments: ["科室1", "科室2", "科室3"],
      doctors: [],
      transactionCategories: ["类别1", "类别2", "类别3"],
      transactionDept: "",
      transactionDoctor: "",
      transactionCategory: "",
      transactionDateRange: [],
      receptionDept: "",
      receptionDoctor: "",
      receptionDateRange: [],
      orderDept: "",
      orderDoctor: "",
      orderDateRange: [],
      departMentArr: [],
      params: { time: "", doctor_id: "", department_id: "" },
      params1: { time: "", doctor_id: "", department_id: "" },
      params2: { time: "", doctor_id: "", department_id: "" },
    };
  },
  computed: {
    formattedTransactionAmount() {
      return this.formatNumber(this.totalTransactionAmount);
    },
  },
  mounted() {
    this.getMoneyStatistics();
    this.getOrderCountStatistics();
    this.getAdviceCountStatistics();
    this.getDepartment();
    this.getDoctorList();
  },
  methods: {
    handleChange(val, label, text) {
      if (text == "交易额") {
        this.params[label] = val;
        this.getMoneyStatistics(this.params);
      }
      if (text == "接诊量") {
        this.params1[label] = val;
        this.getOrderCountStatistics(this.params1);
      }
      if (text == "开单量") {
        this.params2[label] = val;
        this.getAdviceCountStatistics(this.params2);
      }
    },

    getDepartment() {
      ApiDepartment().then((res) => {
        this.departMentArr = res.data;
      });
    },
    getDoctorList() {
      ApigetDoctorList().then((res) => {
        this.doctors = res.data;
      });
    },

    //交易额
    getMoneyStatistics(val) {
      const transactionData = [];
      this.xAxisData = [];
      ApigetMoneyStatistics(val)
        .then((res) => {
          res.data.forEach((item) => {
            this.xAxisData.push(item.date);
            transactionData.push(Number(item.amount));
          });
        })
        .then(() => {
          // 生成交易总额数据

          this.totalTransactionAmount = this.calculateTotal(transactionData);

          // 初始化柱状图（交易总额统计）
          const barChart = echarts.init(document.getElementById("bar-chart"));
          const barOption = {
            title: {
              text: `交易总额：${this.formattedTransactionAmount} (单位：元)`,
            },
            xAxis: {
              type: "category",
              data: this.xAxisData,
            },
            yAxis: {
              type: "value",
            },
            series: [
              {
                data: transactionData,
                type: "bar",
                label: {
                  show: true,
                  position: "top",
                  formatter: (params) => {
                    return this.formatNumber(params.value);
                  },
                },
              },
            ],
          };
          barChart.setOption(barOption);
        });
    },
    //接诊量
    getOrderCountStatistics(val) {
      const xAxisData = [];
      const receptionData = [];
      ApigetOrderCountStatistics(val)
        .then((res) => {
          res.data.forEach((item) => {
            xAxisData.push(item.date);
            receptionData.push(item.count);
          });
          // 生成接诊总量数据，数量控制在 100 以内
        })
        .then(() => {
          this.totalReceptionAmount = this.calculateTotal(receptionData);
          // 初始化第一个折线图（接诊总量统计）
          const lineChart1 = echarts.init(
            document.getElementById("line-chart-1")
          );
          const lineOption1 = {
            title: {
              text: `接诊总量：${this.totalReceptionAmount} (单位：人次)`,
            },
            xAxis: {
              type: "category",
              data: xAxisData,
            },
            yAxis: {
              type: "value",
            },
            series: [
              {
                data: receptionData,
                type: "line",
                label: {
                  show: true,
                  position: "top",
                },
              },
            ],
          };
          lineChart1.setOption(lineOption1);
        });
    },
    //开单量
    getAdviceCountStatistics(val) {
      const xAxisData = [];
      const orderData = [];
      ApigetAdviceCountStatistics(val)
        .then((res) => {
          res.data.forEach((item) => {
            xAxisData.push(item.date);
            orderData.push(item.count);
          });
        })
        .then(() => {
          // 生成开单总量数据，数量控制在 100 以内
          this.totalOrderAmount = this.calculateTotal(orderData);
          // 初始化第二个折线图（开单总量统计）
          const lineChart2 = echarts.init(
            document.getElementById("line-chart-2")
          );
          const lineOption2 = {
            title: {
              text: `开单总量：${this.totalOrderAmount} (单位：人次)`,
            },
            xAxis: {
              type: "category",
              data: xAxisData,
            },
            yAxis: {
              type: "value",
            },
            series: [
              {
                data: orderData,
                type: "line",
                label: {
                  show: true,
                  position: "top",
                },
              },
            ],
          };
          lineChart2.setOption(lineOption2);
        });
    },

    getLastSevenDays() {
      const dates = [];
      const now = new Date();
      for (let i = 6; i >= 0; i--) {
        const date = new Date(now.getTime() - i * 24 * 60 * 60 * 1000);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        dates.push(`${year}-${month}-${day}`);
      }
      return dates;
    },
    generateRandomData(max = 1000) {
      const data = [];
      for (let i = 0; i < 7; i++) {
        data.push(Math.floor(Math.random() * max));
      }
      return data;
    },

    calculateTotal(data) {
      return data.reduce((sum, value) => sum + value, 0);
    },
    formatNumber(num) {
      return num.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    },
    handleTransactionQuery() {
      console.log("交易总额查询参数：", {
        dept: this.transactionDept,
        doctor: this.transactionDoctor,
        category: this.transactionCategory,
        dateRange: this.transactionDateRange,
      });
    },
    handleReceptionQuery() {
      console.log("接诊总量查询参数：", {
        dept: this.receptionDept,
        doctor: this.receptionDoctor,
        dateRange: this.receptionDateRange,
      });
    },
    handleOrderQuery() {
      console.log("开单总量查询参数：", {
        dept: this.orderDept,
        doctor: this.orderDoctor,
        dateRange: this.orderDateRange,
      });
    },
  },
};
</script>

<style scoped>
html,
body,
#app {
  height: 100%;
  margin: 0;
  padding: 0;
}

#app {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  gap: 10px;
  padding:0 10px;
  box-sizing: border-box;
}

.chart-container:nth-child(1) {
  grid-column: 1 / 3;
}

.chart-container {

  background-color: white;
  border: 1px solid white;
  border-radius: 5px;
  padding: 10px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

h2 {
  margin: 0 0 10px 0;
  font-size: 18px;
}

.search-boxes {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.chart {
  width: 100%;
  height: calc(100% - 60px); /* 减去标题、搜索框及相关间距的高度 */
}
</style>